const db = require('../db/index');

const bcrypt = require('bcryptjs');

// 导入nodejs中crypto模块生成唯一id
const crypto = require('crypto');
// 导入fs处理文件
const fs = require('fs');

// 上传头像
exports.uploadAvatar = (req, res) => {
  const onlyId = crypto.randomUUID();
  let oldName = req.files[0].filename;
  let newName = Buffer.from(req.files[0].originalname, 'latin1').toString('utf8');
  // fs.renameSync( oldPath, newPath )
  fs.renameSync(`./public/upload/${oldName}`, `./public/upload/${newName}`);
  // image 这是表名字
  const sql = 'insert into image set ?';
  db.query(sql, {
    image_url: `http://127.0.0.1:3000/upload/${newName}`,
    onlyId
  }, (err, results) => {
    if (err) return res.cc(err)
    if (results.affectedRows !== 1) return res.cc('头像上传失败')
    res.send({
      status: 0,
      message: '头像上传成功',
      url: `http://127.0.0.1:3000/upload/${newName}`
    })
  })
}

// 绑定账号
exports.bindAccount = (req, res) => {
  const {
    account,
    url,
    onlyId
  } = req.body;

  // 通过onlyId更新账号信息
  let sql = 'update image set account = ? where onlyId = ?';
  db.query(sql, [account, onlyId], (err, results) => {
    if (err) return res.cc(err)

    if (results.affectedRows === 1) {
      let sql1 = 'update users set image_url = ? where account = ?';
      db.query(sql1, [url, account], (err, results) => {
        if (err) return res.cc(err)
        if (results.affectedRows === 1) {
          res.send({
            status: 0,
            message: '账号绑定成功'
          })
        }
      })
    }
  })
}

// 修改用户密码
exports.updatePassword = (req, res) => {
  let {
    id,
    oldPassword,
    newPassword
  } = req.body;
  let sql = 'select password from users where id = ?';
  db.query(sql, id, (err, results) => {
    if (err) return res.cc(err)
    if (results.length === 0) return res.cc('用户不存在')
    const compareResult = bcrypt.compareSync(oldPassword, results[0].password)
    if (!compareResult) {
      res.send({
        status: 1,
        message: '原密码错误'
      })
    }
    // 对新密码进行加密,并进行截取
    let encryPassword = bcrypt.hashSync(newPassword, 10);
    let sql1 = 'update users set password = ? where id = ?';
    db.query(sql1, [encryPassword, id], (err, results) => {
      if (err) return res.cc(err)
      if (results.affectedRows === 1) {
        res.send({
          status: 0,
          message: '密码修改成功'
        })
      }
    })
  })
}

// 获取用户信息 id   get请求参数在  req.query对象里面  post请求参数在req.body对象里面
exports.getUserInfo = (req, res) => {
  let sql = 'select * from users where id = ?';
  db.query(sql, req.query.id, (err, results) => {
    if (err) return res.cc(err)
    // select 语句是不返回  affectedRows 字段
    res.send({
      status: 0,
      results: results[0]
    })
  })
}
// 通过id 修改用户姓名
exports.updateName = (req, res) => {
  let {
    id,
    name
  } = req.body
  let sql = 'update users set name = ? where id = ?';

  db.query(sql, [name, id], (err, results) => {
    if (err) return res.cc(err)
    // select 语句是不返回  affectedRows 字段
    res.send({
      status: 0,
      message: '修改姓名成功'
    })
  })
}
// 通过id 修改用户性别
exports.updateSex = (req, res) => {
  let {
    id,
    sex
  } = req.body
  let sql = 'update users set sex = ? where id = ?';

  db.query(sql, [sex, id], (err, results) => {
    if (err) return res.cc(err)
    // select 语句是不返回  affectedRows 字段
    res.send({
      status: 0,
      message: '修改性别成功'
    })
  })
}
// 通过id 修改用户邮箱
exports.updateEmail = (req, res) => {
  let {
    id,
    email
  } = req.body
  let sql = 'update users set email = ? where id = ?';

  db.query(sql, [email, id], (err, results) => {
    if (err) return res.cc(err)
    // select 语句是不返回  affectedRows 字段
    res.send({
      status: 0,
      message: '修改邮箱成功'
    })
  })
}

// 验证账号和邮箱是否一致
exports.verifyAccountAndEmail = (req, res) => {
  let {
    account,
    email
  } = req.body;
  let sql = 'select email,id from users where account = ?';
  db.query(sql, account, (err, results) => {
    if (err) return res.cc(err)
    if (email === results[0].email) {
      res.send({
        status: 0,
        id: results[0].id,
        message: '账号和邮箱一致'
      })
    } else {
      res.send({
        status: 1,
        message: '查询失败'
      })
    }
  })
}

// 登录页面修改密码
exports.changePassword = (req, res) => {
  let {
    id,
    newPassword
  } = req.body;
  let sql = 'update users set password = ? where id = ?';
  // 对新密码进行加密,并进行截取
  let encryPassword = bcrypt.hashSync(newPassword, 10);
  db.query(sql, [encryPassword, id], (err, results) => {
    if (err) return res.cc(err)
    if (results.affectedRows === 1) {
      res.send({
        status: 0,
        message: '密码修改成功'
      })
    }
  })
}

// 用户管理

// 添加管理员
exports.createAdmin = (req, res) => {
  let {
    name,
    account,
    password,
    email,
    sex,
    department,
    identity,
  } = req.body;
  // 判断账号是否已存在
  let sql = 'select * from users where account = ?';
  db.query(sql, account, (err, results) => {
    if (err) return res.cc(err)
    if (results.length > 0) {
      res.send({
        status: 1,
        message: '该账号已存在'
      })
    }
    // 密码进行加密
    let encryPassword = bcrypt.hashSync(password, 10);
    let sql1 = 'insert into users set ?';
    const create_time = new Date();
    db.query(sql1, {
      name,
      account,
      password: encryPassword,
      email,
      sex,
      department,
      identity,
      create_time,
      status: 0 // 默认冻结状态
    }, (err, results) => {
      if (err) return res.cc(err)
      if (results.affectedRows !== 1) {
        res.send({
          status: 1,
          message: '添加管理失败'
        })
      } else {
        res.send({
          status: 0,
          message: '添加管理成功'
        })
      }

    })
  })
}
// 通过身份来---获取管理员列表
exports.getAdminList = (req, res) => {
  let sql = 'select * from users where identity =?';
  db.query(sql, req.query.identity, (err, results) => {
    if (err) return res.cc(err)
    res.send({
      status: 0,
      results
    })
  })
}
// 通过部门---获取管理员列表
exports.getAdminListByDepartment = (req, res) => {
  let sql = 'select * from users where department =?';
  db.query(sql, req.query.department, (err, results) => {
    if (err) return res.cc(err)
    res.send({
      status: 0,
      results
    })
  })
}

// 修改管理员信息
exports.editAdmin = (req, res) => {
  let {
    id,
    name,
    sex,
    department,
    email
  } = req.body;
  let date = new Date();
  let updateConent = {
    id,
    name,
    sex,
    department,
    email,
    update_time: date
  }
  // 判断是否修改部门，如果修改就更新  read_list read_status字段
  let sql0 = 'select department from users where id=?';
  db.query(sql0, id, (err, results) => {
    if (err) return res.cc(err);
    if (results[0].department !== department) {
      updateConent.read_list = null;
      updateConent.read_status = 0;
    }
    let sql = 'update users set ? where id = ?';
    db.query(sql, [updateConent, id], (err, results) => {
      if (err) return res.cc(err)
      if (results.affectedRows !== 1) {
        res.send({
          status: 1,
          message: '修改管理员信息失败'
        })
      } else {
        res.send({
          status: 0,
          message: '修改管理员信息成功'
        })
      }
    })
  })
}

// 对管理员进行取消赋权操作
exports.cancelAdmin = (req, res) => {
  let sql = 'update users set identity = ? where id =?';
  let identity = '用户';
  db.query(sql, [identity, req.body.id], (err, results) => {
    if (err) return res.cc(err)
    if (results.affectedRows !== 1) {
      res.send({
        status: 1,
        message: '取消管理员权限失败'
      })
    } else {
      res.send({
        status: 0,
        message: '取消管理员权限成功'
      })
    }
  })
}
// 对普通用户进行赋权操作
exports.toBeAdmin = (req, res) => {
  let {
    id,
    identity,
  } = req.body;
  let date = new Date()
  let sql = 'update users set identity = ?,update_time=? where id =?';
  db.query(sql, [identity, date, id], (err, results) => {
    if (err) return res.cc(err)
    if (results.affectedRows !== 1) {
      res.send({
        status: 1,
        message: '赋权失败'
      })
    } else {
      res.send({
        status: 0,
        message: '赋权成功'
      })
    }
  })
}

// 通过账号获取用户   通过get 发送的请求  参数在req.query中取    通过post发送的请求  参数在req.body中取
exports.searchUsersByAccount = (req, res) => {
  let sql = 'select * from users where account = ?';
  db.query(sql, req.query.account, (err, results) => {
    if (err) return res.cc(err)
    res.send({
      status: 0,
      results
    })
  })
}

// 冻结用户
exports.freezeUser = (req, res) => {
  let sql = 'update users set status = ? where id =?';
  let status = 1;
  db.query(sql, [status, req.body.id], (err, results) => {
    if (err) return res.cc(err)
    if (results.affectedRows !== 1) {
      res.send({
        status: 1,
        message: '冻结用户失败'
      })
    } else {
      res.send({
        status: 0,
        message: '冻结用户成功'
      })
    }
  })
}
// 解冻用户
exports.thawUser = (req, res) => {
  let sql = 'update users set status = ? where id =?';
  let status = 0;
  db.query(sql, [status, req.body.id], (err, results) => {
    if (err) return res.cc(err)
    if (results.affectedRows !== 1) {
      res.send({
        status: 1,
        message: '解冻用户失败'
      })
    } else {
      res.send({
        status: 0,
        message: '解冻用户成功'
      })
    }
  })
}

// 获取冻结用户列表
exports.getFreezeUsers = (req, res) => {
  let sql = 'select * from users where status = 1';
  db.query(sql, (err, results) => {
    if (err) return res.cc(err)
    res.send({
      status: 0,
      results
    })
  })
}

// 注销/删除用户
exports.deleteUser = (req, res) => {
  let sql = 'delete from users where id=?';
  db.query(sql, req.body.id, (err, results) => {
    console.log('删除用户', results);

    if (err) return res.cc(err)
    // 删除image中关联的账号的图片
    let sql1 = 'delete from image where account = ?';
    db.query(sql1, req.body.account, (err, results) => {
      if (err) return res.cc(err)
      res.send({
        status: 0,
        message: '删除用户成功'
      })
    })
  })
}

// 分页查询管理员的数据和总数
exports.getAdminPageList = (req, res) => {
  let sql = 'select * from users where identity = ?';
  let identity = req.query.identity;
  let total = 0;
  db.query(sql, identity, (err, results) => {
    if (err) return res.cc(err)
    total = results.length;
  })
  // 每页查询一条数据
  let sql1 = `select * from users where identity = ? limit ${req.query.pageSize} offset ${req.query.currentPage - 1}`;
  db.query(sql1, identity, (err, results) => {
    if (err) return res.cc(err)
    res.send({
      status: 0,
      total,
      results
    })
  })
}